package com.example.javabase.multithread.readwritelock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author He Changjie on 2021/7/11
 */
public class RWDictionary {
    private final Map<String, Object> m = new HashMap<>();
    private final ReadWriteLock rwl = new ReentrantReadWriteLock(true);
    private final Lock r = rwl.readLock();
    private final Lock w = rwl.writeLock();

    public Object get(String key){
        r.lock();
        try {
            return m.get(key);
        } finally {
            r.unlock();
        }
    }

    protected String[] allKeys(){
        r.lock();
        try {
            return m.keySet().toArray(new String[0]);
        } finally {
            r.unlock();
        }
    }

    public Object put(String key, Object value){
        w.lock();
        try {
            return m.put(key, value);
        } finally {
            w.unlock();
        }
    }

    public void clear(){
        w.lock();
        try {
            m.clear();
        } finally {
            w.unlock();
        }
    }
}
